<template>
  <el-row :gutter="10">
    <el-col :span="12">
      <el-card>
        <el-descriptions
          title="改造详情"
          :column="2"
          :labelStyle="labelStyle"
          border
        >
          <el-descriptions-item label="乡镇">{{
                                           community.remouldTownName
                                           }}
          </el-descriptions-item>
          <el-descriptions-item label="社区">{{
                                           community.orgName
                                           }}
          </el-descriptions-item>
          <el-descriptions-item label="计划开始时间">{{
                                               exData.startTime
                                               }}
          </el-descriptions-item>
          <el-descriptions-item label="计划结束时间">{{
                                               exData.endTime
                                               }}
          </el-descriptions-item>
          <el-descriptions-item label="改造牵头人">{{
                                              exData.lerderUserName
                                              }}
          </el-descriptions-item>
          <el-descriptions-item label="联系方式">{{
                                             exData.lerderUserMobile
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">{{
                                           community.status | keyText("BARRIER_FREE_STATUS")
                                           }}
          </el-descriptions-item>
          <el-descriptions-item label="可下发数量">
            {{ community.taskCount }}
          </el-descriptions-item>
        </el-descriptions>
        <div class="opt">
          <el-button
            v-if="community.status == 'NOT_REPORT'"
            type="primary"
            @click="report"
          >
            汇总结果上报
          </el-button>
          <el-button
            v-if="community.status === 'RETURN'"
            type="primary"
            @click="report"
          >
            重新上报
          </el-button>
          <el-button
            v-if="['NOT_REPORT','RETURN'].includes(community.status)"
            type="success"
            :disabled="personnelDisabled"
            @click="select"
          >
            选择无障碍改造人员
          </el-button>
          <el-button @click="$parent.who = 'communityTable'">
            返回
          </el-button>
        </div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card>
        <el-descriptions title="无障碍改造人员列表"></el-descriptions>
        <div v-if="records.length !== 0">
          <template v-for="item in records">
            <div :key="item.id" style="margin-bottom:20px">
              <el-descriptions :labelStyle="labelStyle" :column="2" border>
                <el-descriptions-item
                  label="姓名"
                  :contentStyle="{ width: '150px' }"
                >
                  {{ item.name }}
                </el-descriptions-item>
                <el-descriptions-item label="联系方式">
                  {{ item.linkmanPhone }}
                </el-descriptions-item>
                <el-descriptions-item label="改造地址">
                  {{ item.address }}
                </el-descriptions-item>
              </el-descriptions>
              <div class="desAfter">
                <span style="cursor: pointer" @click="view(item.id)">
                  查看详情
                </span>
                <span
                  v-if="['RETURN','NOT_REPORT'].includes(community.status)"
                  style="cursor: pointer;color:#F56C6C;margin-left: 10px"
                  @click="del(item.id)"
                >
                  删除
                </span>
              </div>
            </div>
          </template>
          <div style="text-align:center">
            <el-pagination
              style="display:inline"
              background
              layout="total, prev, pager, next"
              :page-size="5"
              :total="total"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </div>
        </div>
        <div v-else>
          <el-empty description="暂无数据"></el-empty>
        </div>
      </el-card>
    </el-col>
    <el-dialog
      title="选择无障碍改造人员"
      :visible.sync="dialogVisible"
      width="60%"
      top="10vh"
      :close-on-click-modal="false"
      @close="close"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-descriptions
            style="margin-top:20px"
            title="改造人员"
          ></el-descriptions>
          <el-select
            style="width:100%"
            v-model="person"
            placeholder="请选择人员"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <!-- file -->
          <el-descriptions
            style="margin-top:20px"
            title="附件"
          ></el-descriptions>
          <el-upload
            ref="upload"
            class="upload"
            drag
            :action="url"
            :headers="headers"
            multiple
            :on-success="successHandle"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :limit="10"
            :file-list="fileList"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
          <el-descriptions
            style="margin-top:20px"
            title="改造地址"
            :column="1"
            :labelStyle="{ width: '80px' }"
            border
          >
            <el-descriptions-item label="详细地址">{{
                                               address
                                               }}
            </el-descriptions-item>
            <el-descriptions-item label="经度">{{
                                             position.lng
                                             }}
            </el-descriptions-item>
            <el-descriptions-item label="纬度">{{
                                             position.lat
                                             }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="16">
          <el-autocomplete
            v-model.trim="mapLocation.address"
            :fetch-suggestions="querySearch"
            placeholder="请输入详细地址"
            style="width: 100%;margin-bottom: 10px"
            :trigger-on-focus="false"
            @select="handleSelect"
          />
          <!-- baidu map -->
          <baidu-map
            v-if="dialogVisible"
            class="bm-view"
            :center="center"
            :zoom="zoom"
            @click="setPoint"
            scroll-wheel-zoom
            @ready="handlerBMap"
          >
            <!-- 单个点 -->
            <bm-marker :position="position" />
            <!-- 定位 -->
            <bm-geolocation
              anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
              :showAddressBar="true"
              :autoLocation="true"
            />
            <!-- 城市列表控件 -->
            <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT" />
            <!-- 地图类型 -->
            <bm-map-type
              :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
              anchor="BMAP_ANCHOR_TOP_LEFT"
            />
          </baidu-map>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="close">取消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="改造人员详情"
      :visible.sync="personVisible"
      width="40%"
      top="15vh"
    >
      <el-descriptions :labelStyle="labelStyle" :column="2" border>
        <el-descriptions-item label="姓名" :span="2">
          {{ personInfo.name }}
        </el-descriptions-item>
        <el-descriptions-item label="联系人">
          {{ personInfo.linkman }}
        </el-descriptions-item>
        <el-descriptions-item label="联系方式">
          {{ personInfo.linkmanPhone }}
        </el-descriptions-item>
        <el-descriptions-item label="改造地址" :span="2">
          {{ personInfo.address }}
        </el-descriptions-item>
        <el-descriptions-item label="经度">
          {{ personInfo.lng }}
        </el-descriptions-item>
        <el-descriptions-item label="纬度">
          {{ personInfo.lat }}
        </el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">
          {{ personInfo.status | keyText("BARRIER_FREE_STATUS") }}
        </el-descriptions-item>
        <el-descriptions-item label="附件" :span="2" v-if="personInfo.file">
          <div style="display: inline-block">
            <div
              v-for="(item, index) in JSON.parse(personInfo.file)"
              :key="index"
              style="margin-bottom: 4px"
            >
              <a class="article_title_a" @click="previewDetail(item.id)">
                <i class="el-icon-files mr5" />{{ item.fileName }}
              </a>
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </el-row>
</template>

<script>
export default {
  name: "communityDetail",
  props: {
    obj: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    personnelDisabled() {
      return this.total >= this.community.taskCount
    }
  },
  activated() {
    this.exData = this.obj;
    this.getVillage();
  },
  data() {
    return {
      fileList: [],
      exData: this.obj,
      // url: window.api.uploadUrl1,
      url: window.api.sysUploadUrl + '?path=barrier',
      headers: {
        userRole: "ADMIN",
        token: sessionStorage.getItem("token")
      },
      filePath: "",
      labelStyle: {
        width: "120px",
        textAlign: "center"
      },
      total: 1,
      pageIndex: 1,
      community: {},
      personInfo: {},
      records: [],
      person: "",
      options: [],
      dialogVisible: false,
      personVisible: false,
      center: { lng: 112.460608, lat: 34.603461 }, // 默认洛阳坐标
      position: {},
      zoom: 12,
      address: "",
      mapLocation: {
        address: undefined
      },
      map: undefined
    };
  },
  methods: {
    // 获取map对象
    handlerBMap({ map }) {
      this.map = map
    },
    querySearch(queryString, cb) {
      let options = {
        onSearchComplete: (res) => {
          let result = []
          if (local.getStatus() === 0) {
            for (let i = 0; i < res.getCurrentNumPois(); i++) {
              let poi = res.getPoi(i)
              let item = { value: poi.address + poi.title, point: poi.point }
              result.push(item)
            }
          }
          cb(result)
        }
      }
      let local = new BMap.LocalSearch(this.map, options)
      local.search(queryString)
    },
    handleSelect(item) {
      this.makerCenter(item.point)
      this.setPoint(item)
    },
    makerCenter(point) {
      if (this.map) {
        this.center.lng = point.lng
        this.center.lat = point.lat
      }
    },
    previewDetail(val) {
      this.openTabPage(
        window.api.preFile +
        "?url=" +
        window.api.secretFilePreview +
        val +
        "?token=" +
        window.sessionStorage.getItem("token")
      );
    },
    successHandle(res, file, fileList) {
      this.filePath = "";
      let ids = [];
      fileList.map(item => {
        if (item.response && item.response.id) {
          ids.push(item.response);
        }
      });
      this.filePath = JSON.stringify(ids);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 10 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove(file, fileList) {
      this.filePath = "";
      let ids = [];
      fileList.map(item => {
        if (item.response && item.response.id) {
          ids.push(item.response);
        }
      });
      this.filePath = ids.length ? JSON.stringify(ids) : '';
    },
    // 上报
    report() {
      this.$confirm("确认上报?", "提示", {
        type: "success"
      }).then(() => {
        this.API.report({
          remouldId: this.exData.id,
          villageId: this.community.id
        }).then(res => {
          this.success("上报成功");
          this.getVillage();
        });
      });
    },
    getVillage() {
      // 获取当前社区信息
      this.API.getRemouldVillage({ remouldId: this.exData.id }).then(res => {
        this.community = res.data;
        // 获取汇总结果
        this.getList();
      });
    },
    // 选人
    select() {
      this.dialogVisible = true;
      this.API.getByCommittee().then(res => {
        this.options = res.data;
      });
    },
    // 地图坐标
    setPoint({ point }) {
      this.position = point;
      let geocoder = new BMap.Geocoder(); //创建地址解析器的实例
      geocoder.getLocation(point, rs => {
        this.address = rs.address;
      });
    },
    // 查看详情
    getList() {
      this.API.getVillagePersonPageList({
        remouldId: this.exData.id,
        villageId: this.community.id,
        pageIndex: this.pageIndex,
        pageSize: 5
      }).then(res => {
        this.total = res.data.total;
        this.records = res.data.records;
      });
    },
    // 查看详情
    save() {
      if (!this.person) {
        return this.$message({
          message: "请选择改造人员",
          type: "warning"
        });
      }
      if (!this.filePath) {
        return this.$message({
          message: "请上传附件",
          type: "warning"
        });
      }
      if (!this.address) {
        return this.$message({
          message: "请在地图中标记改造地址",
          type: "warning"
        });
      }
      let slt = this.options.find(i => i.id == this.person);
      let { id, userId, name, tutelageName, tutelagePhone } = slt;
      let { lng, lat } = this.position;
      let body = {
        remouldId: this.exData.id,
        remouldVillageId: this.community.id,
        personId: id,
        userId,
        name,
        linkman: tutelageName,
        linkmanPhone: tutelagePhone,
        address: this.address,
        lng,
        lat,
        file: this.filePath
      };
      this.$confirm("确认保存?", "提示", {
        type: "success"
      }).then(() => {
        this.API.addOrUpdateRemouldVillagePerson({ body }).then(res => {
          this.success("添加成功!");
          this.close()
          this.getList();
        });
      });
    },
    // 查看详情
    view(id) {
      this.personVisible = true;
      this.API.getRemouldVillagePersonById({ id }).then(res => {
        this.personInfo = res.data;
      });
    },
    // 删除
    del(id) {
      this.$confirm("确认删除?", "提示", {}).then(() => {
        this.API.deleteRemouldVillagePersonById({ id }).then(() => {
          this.success('删除成功')
          this.getList();
        })
      }).catch(() => {
      });
    },
    // 分页回调
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.getList();
    },
    close() {
      this.dialogVisible = false;
      this.address = "";
      this.position = {};
      this.person = "";
      this.filePath = ""
      this.fileList = []
      this.mapLocation.address = undefined;
      this.center = { lng: 112.460608, lat: 34.603461 }
    },
  }
};
</script>

<style scoped>
  .upload >>> .el-upload,
  .upload >>> .el-upload-dragger {
    width: 100%;
  }

  .bm-view >>> .ui_city_change {
    margin-top: 32px !important;
  }

  .opt {
    margin: 20px;
    display: flex;
    justify-content: center;
  }

  .desAfter {
    border: 1px solid #ebeef5;
    border-top: none;
    padding: 12px 10px;
    font-size: 14px;
    color: #409eff;
    text-align: center;
  }

  .bm-view {
    width: 100%;
    height: 500px;
  }
</style>
